package com.jeesuite.bestpl.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesuite.bestpl.dao.entity.UserEntity;
import com.jeesuite.bestpl.dao.entity.UserEntity.UserStatus;
import com.jeesuite.bestpl.dao.mapper.UserEntityMapper;
import com.jeesuite.bestpl.dto.Constants;
import com.jeesuite.bestpl.dto.PageMetaInfo;
import com.jeesuite.bestpl.dto.request.RegisterUserParam;
import com.jeesuite.bestpl.exception.JeesuiteBaseException;
import com.jeesuite.bestpl.security.LoginUserInfo;
import com.jeesuite.bestpl.security.PasswordUtils;
import com.jeesuite.bestpl.security.SecurityUtil;
import com.jeesuite.bestpl.service.UserService;
import com.jeesuite.common.util.BeanCopyUtils;
import com.jeesuite.common.util.FormatValidateUtils;

@Controller
@RequestMapping("/user")
public class UserController {

	
	private @Autowired UserEntityMapper userMapper;
	private @Autowired UserService userService;
	
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(Model model){
		if(SecurityUtil.isLogined()){
			throw new JeesuiteBaseException("已经处于登录状态");
		}
		model.addAttribute(PageMetaInfo.ATTR_NAME, PageMetaInfo.current().setModelName("user").setSubTitle("登录"));
		
		return "user/login";
	}
	
	@RequestMapping(value = "register", method = RequestMethod.GET)
	public String register(Model model){
		if(SecurityUtil.isLogined()){
			throw new JeesuiteBaseException("已经处于登录状态");
		}
		model.addAttribute(PageMetaInfo.ATTR_NAME, PageMetaInfo.current().setModelName("user").setSubTitle("注册"));
		
		return "user/reg";
	}

	@RequestMapping(value = "act/register", method = RequestMethod.POST)
	public @ResponseBody LoginUserInfo doRegister(HttpServletRequest request,@RequestBody RegisterUserParam params){
		
		if(SecurityUtil.isLogined()){
			throw new JeesuiteBaseException("已经处于登录状态");
		}

		UserEntity userEntity = BeanCopyUtils.copy(params, UserEntity.class);
		
		userService.createUser(userEntity, null, null);
		
		LoginUserInfo loginUserInfo = new LoginUserInfo(userEntity.getId(),userEntity.getNickname(),userEntity.getUserType());
		loginUserInfo.setAvatar(userEntity.getAvatar());
		
		request.getSession().setAttribute(Constants.LOGIN_SESSION_KEY, loginUserInfo);
		return loginUserInfo;
	}
	
	
	@RequestMapping(value = "act/login", method = RequestMethod.POST)
	public @ResponseBody LoginUserInfo doLogin(HttpServletRequest request,@RequestBody Map<String, String> params){
		if(SecurityUtil.isLogined()){
			throw new JeesuiteBaseException("已经处于登录状态");
		}
		
		String accountName = StringUtils.trimToEmpty(params.get("accountName"));
		String password = StringUtils.trimToEmpty(params.get("password"));
		
		UserEntity userEntity = null;
		if(FormatValidateUtils.isEmail(accountName)){
			userEntity = userMapper.findByEmail(accountName);
		}else if(FormatValidateUtils.isMobile(accountName)){
			userEntity = userMapper.findByMobile(accountName);
		}else{
			userEntity = userMapper.findByName(accountName);
		}
		
		if(userEntity == null || !userEntity.getPassword().equals(PasswordUtils.encrypt(password, userEntity.getUsername()))){
			throw new JeesuiteBaseException(4001,"账号或密码错误");
		}
		
		LoginUserInfo loginUserInfo =  new LoginUserInfo(userEntity.getId(),userEntity.getUsername(),userEntity.getUserType());
		if(!UserStatus.a.name().equals(userEntity.getStatus())){
			throw new JeesuiteBaseException(1001, "该账号已停用或未激活");
		}
		request.getSession().setAttribute(Constants.LOGIN_SESSION_KEY, loginUserInfo);
		return loginUserInfo;
	}
	
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request){
		request.getSession().removeAttribute(Constants.LOGIN_SESSION_KEY);
		return "redirect:" + request.getContextPath() + "/user/login"; 
	}
	
	@RequestMapping(value = "forget_password", method = RequestMethod.GET)
	public String findPass(Model model){
		if(SecurityUtil.isLogined()){
			throw new JeesuiteBaseException("已经处于登录状态");
		}
		model.addAttribute(PageMetaInfo.ATTR_NAME, PageMetaInfo.current().setModelName("user").setSubTitle("找回密码"));
		return "user/forget";
	}
	
	@RequestMapping(value = "act/reset_password", method = RequestMethod.POST)
	public Boolean resetPassword(HttpServletRequest request,@RequestBody Map<String, String> params){
		if(SecurityUtil.isLogined()){
			throw new JeesuiteBaseException("已经处于登录状态");
		}
		
		String email = StringUtils.trimToEmpty(params.get("email"));
		String password = StringUtils.trimToEmpty(params.get("password"));
		
		UserEntity userEntity = userMapper.findByEmail(email);
		userEntity.setPassword(PasswordUtils.encrypt(password, userEntity.getUsername()));
		userMapper.updateByPrimaryKeySelective(userEntity);
		
		return true;
	}
	
	@RequestMapping(value = "act/bind", method = RequestMethod.POST)
	public Boolean bindSnsAccount(HttpServletRequest request,@RequestBody Map<String, Object> params){
		if(SecurityUtil.isLogined()){
			throw new JeesuiteBaseException("已经处于登录状态");
		}
		
		Object openIdInfo = request.getSession().getAttribute("oauth_openid");
		if(openIdInfo == null)throw new JeesuiteBaseException("非法请求");
		
		
		String[] openIdInfos = openIdInfo.toString().split(":");
		UserEntity userEntity = BeanCopyUtils.mapToBean(params, UserEntity.class);
		userService.createUser(userEntity, openIdInfos[0], openIdInfos[1]);
		
		request.getSession().removeAttribute("oauth_openid");
		
		return true;
	}
	
}
